package pcron

import (
	"sync"

	"gitee.com/linxing_3/sr-core/plugins/log"
	"gitee.com/linxing_3/sr-core/relay"
	"gitee.com/linxing_3/sr-core/yerr"
	"gitee.com/mkwchecking/sr-admin/pkg/instance"
	"github.com/robfig/cron/v3"
)

var cornLock = &sync.Mutex{}

func UpsertCronService() (*cron.Cron, error) {
	cornLock.Lock()
	defer cornLock.Unlock()

	c, err := instance.GetOrInit(YCronKey{}, initCronService)
	if err != nil {
		return nil, err
	} else if c == nil || *c == nil {
		return nil, yerr.ErrBizPluginNotFound.Errorf("cron may not init ")
	}

	return *c, nil
}

func initCronService() (*cron.Cron, error) {

	// 检查上下文中是否已注册
	if c, ok := FromCtx(relay.Context()); ok {
		return c, nil
	}

	// 新建
	return cron.New(
		cron.WithLogger(Logger(log.GetDefault())),
	), nil
}
